<template>
  <el-card>
    <BreadCrumb />
    <el-form ref="FormRef" :model="form" :rules="FormRules" label-width="120px">
      <el-form-item label="教师工号" prop="teacherId">
        <el-input v-model="form.teacherId" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item label="教师姓名" prop="username">
        <el-input v-model="form.username" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-select
          v-model="form.roleId"
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in roleNameList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否禁用">
        <el-radio v-model="form.disabled" :label="true">
          是
        </el-radio>
        <el-radio v-model="form.disabled" :label="false">
          否
        </el-radio>
      </el-form-item>
      <el-form-item class="form_button">
        <el-button type="primary" :disabled="btnDisabled" @click="updateTeacher()">
          更新
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import BreadCrumb from '@/components/BreadCrumb'
import { isConfirm } from '@/utils/confirm'
import { checkEmail } from '@/utils/checkRules.js'
import { getTeacher, updateTeacher } from '@/api/teacherApi'
import { getRoleNameList } from '@/api/roleApi'
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      // 教师信息表单
      form: {

      },
      // 教师信息表单验证规则
      FormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      // 下拉框角色数据
      roleNameList: [],
      // 更新按钮是否被禁用
      btnDisabled: true
    }
  },
  created() {
    // 获取下拉框角色信息数据
    this.getRoleNameList()
    // 初始化表单信息
    this.getTeacher(this.$route.params.teacherId)
    // 解禁按钮
    this.btnDisabled = false
  },
  methods: {
    // 根据 id 查询教师信息
    async getTeacher(id) {
      const { data: res } = await getTeacher(id)
      this.form = res.teacher
    },
    // 获取角色名称信息数据
    async getRoleNameList() {
      const { data: res } = await getRoleNameList()
      this.roleNameList = res.roleNameList
    },
    // 更新教师信息
    updateTeacher() {
      // 表单预校验
      this.$refs.FormRef.validate(async valid => {
        if (!valid) return
        // 更新确认
        if (await isConfirm('是否更新该教师信息？')) {
          await updateTeacher(this.form)
          this.$message.success('更新成功')
          // 跳转上一个路由
          this.$router.go(-1)
        }
      })
    }
  }
}
</script>

<style scoped>
.el-input {
  width: 400px;
}
.el-form-item {
  margin: 0 0 50px -30px;
}
</style>
